package com.hong.qrpc.server;

import com.hong.qrpc.RequestHandler;
import com.hong.qrpc.TransportServer;
import com.hong.qrpc.handler.factory.HandlerFactory;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.net.InetSocketAddress;

/**
 * @Author HQT
 * @Date 2022/8/8 20:31
 */
public class NettyTransportServer implements TransportServer {
    private int port;
    private RequestHandler requestHandler;
    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;
    private int protocolType;

    public NettyTransportServer() {
    }

    @Override
    public void init(int port, int protocolType, RequestHandler handler) {
        requestHandler = handler;
        this.port = port;
        this.protocolType = protocolType;
    }

    @Override
    public void start() {
        bossGroup = new NioEventLoopGroup();
        workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    .option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator())
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline()
                                    .addLast(HandlerFactory.getRequestHandler(protocolType, requestHandler, ch));
                        }
                    });

            // Bind and start to accept incoming connections.
            ChannelFuture f = b.bind(port).sync();
            //获取随机生成的端口并且赋值给port成员变量
            InetSocketAddress localAddress = (InetSocketAddress) f.channel().localAddress();
            int port = localAddress.getPort();
            this.port = port;
            // Wait until the server socket is closed.
            // In this example, this does not happen, but you can do that to gracefully
            // shut down your server.
            synchronized (this) {
                this.notifyAll();
            }
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    @Override
    public void stop() {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }

    @Override
    public int getPort() {
        return port;
    }
}
